package com.rxh.controller;

import com.rxh.pojo.base.Page;
import com.rxh.pojo.base.PageResult;
import com.rxh.pojo.merchant.MerchantInfo;
import com.rxh.pojo.merchant.MerchantPay;
import com.rxh.pojo.merchant.MerchantUser;
import com.rxh.pojo.merchant.MerchantWebSite;
import com.rxh.service.*;
import com.rxh.spring.annotation.SystemLogInfo;
import com.rxh.util.UserInfoUtils;
import com.rxh.utils.GlobalConfiguration;
import com.rxh.utils.SystemConstant;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: 陈俊雄
 * Date: 2018/3/21
 * Time: 14:51
 * Project: Management
 * Package: com.rxh.controller
 */
@Controller
@RequestMapping(value = "/merchant")
@ResponseBody
public class MerchantController {
    @Resource
    private MerchantService merchantService;

    @Resource
    private BusinessMoneyService businessMoneyService;

    @Resource
    private FinanceService financeService;

    @Resource
    private GlobalConfiguration globalConfiguration;

    @Resource
    private MerchantUserService merchantUserService;

    @Resource
    private BCryptPasswordEncoder passwordEncoder;

    @Resource
    private SystemService systemService;

    @Resource
    private ConstantService constantService;

    @Autowired
    ServletContext servletContext;

    @SystemLogInfo(description = "获取商户网址列表")
    @RequestMapping(value = "/getAllMerchantWebSite")
    public List<MerchantWebSite> getAllMerchantWebSite() {
        return merchantService.selectMerchantWebSiteByMerchantId(UserInfoUtils.getMerchantId());
    }

    @SystemLogInfo(description = "获取商户余额")
    @RequestMapping(value = "/getMerchantBalance")
    public BigDecimal getMerchantBalance() {
        return businessMoneyService.getMerchantBalance(UserInfoUtils.getMerchantId()).getUsableAmount();
    }

    @SystemLogInfo(description = "商户余额提现")
    @RequestMapping(value = "/financeDrawingApplication")
    public Boolean financeDrawingApplication(@RequestBody BigDecimal amount) {
        return financeService.addFinanceDrawing(UserInfoUtils.getMerchantId(), SystemConstant.FINANCE_DRAWING_TYPE_MERCHANT,
                SystemConstant.CURRENCY_CNY, amount, SystemConstant.CURRENCY_CNY, new BigDecimal(1), UserInfoUtils.getUserName());
    }

    @RequestMapping(value = "/getFinanceDrawingInit")
    public Map<String, Object> getFinanceDrawingInit() {
        return financeService.getFinanceDrawingInit();
    }

    @SystemLogInfo(description = "余额提现查询")
    @RequestMapping(value = "/getFinanceDrawing")
    public PageResult getFinanceDrawing(@RequestBody Page page) {
        page.getSearchInfo().setMerId(UserInfoUtils.getMerchantId());
        return financeService.getFinanceDrawing(page);
    }

    @RequestMapping(value = "/getBaseInformationInit")
    public Map<String, Object> getBaseInformationInit() {
        Map<String, Object> init = new HashMap<>();
        init.put("merchantInfo", merchantService.selectMerchantInfoByMerchantId(UserInfoUtils.getMerchantId()));
        init.put("provinceInfo", systemService.getAreaInfoByCountryCode(SystemConstant.COUNRTY_CODE_CHN));
        init.put("merchantCategory", constantService.getConstantByGroupName(SystemConstant.MERCHANT_CATEGORY));
        return init;
    }

    @RequestMapping(value = "/uploadMerchantCertificate")
    public String uploadMerchantCertificate(@RequestParam("file") MultipartFile multipartFiles) throws IOException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        Integer merchantId = UserInfoUtils.getMerchantId();
        String certificatePath = globalConfiguration.getFileUploadPath() + merchantId + "/";
        File filePath = new File(certificatePath);
        if (!filePath.exists()) {
            filePath.mkdir();
        }
        certificatePath += dateFormat.format(new Date()) + multipartFiles.getOriginalFilename().substring(multipartFiles.getOriginalFilename().indexOf("."));
        File file = new File(certificatePath);
        multipartFiles.transferTo(file);
        return certificatePath.replace(globalConfiguration.getFileUploadPath(), "");
    }

    @SystemLogInfo(description = "更新商户信息")
    @RequestMapping(value = "/updateMerchantInfo")
    public Boolean updateMerchantInfo(@RequestBody MerchantInfo merchantInfo) {
        return merchantService.updateMerchantInfo(merchantInfo, UserInfoUtils.getUserName());
    }


    @RequestMapping(value = "/getConfigurationInformation")
    public Map<String, Object> getConfigurationInformation() {
        return merchantService.getMerchantSettingInit(UserInfoUtils.getMerchantId());
    }

    @RequestMapping(value = "/getPaymentInformation")
    public Map<String, Object> getPaymentInformation() {
        return merchantService.getMerchantRateInit(UserInfoUtils.getMerchantId());
    }

    @RequestMapping(value = "/getMerchantPay")
    public MerchantPay getSecretKey() {
        return merchantService.selectMerchantPayByRefIdAndRefType(UserInfoUtils.getMerchantId(), SystemConstant.REF_TYPE_MERCHANT);
    }

    @RequestMapping(value = "/updateMerchantPay")
    public Boolean updateMerchantPay(@RequestBody MerchantPay merchantPay) {
        MerchantUser merchantUser = merchantUserService.getUserAndRoleAndPrivilege(UserInfoUtils.getUserName(), UserInfoUtils.getMerchantId());
        // merchantPay.getModifier()为页面输入的登录用户密码
        return passwordEncoder.matches(merchantPay.getModifier(), merchantUser.getPassword()) ?
                merchantService.updateMerchantPay(merchantPay, UserInfoUtils.getUserName()) : false;
    }

    @RequestMapping(value = "/certificateImg", method = RequestMethod.GET)
    public ResponseEntity<byte[]> getImageAsResource(String certificate) throws IOException {
        File img = new File(globalConfiguration.getFileUploadPath() + certificate);
        if (img.exists()) {
            FileInputStream inputStream = new FileInputStream(img);
            byte[] media = IOUtils.toByteArray(inputStream);
            HttpHeaders headers = new HttpHeaders();
            headers.setCacheControl(CacheControl.noCache().getHeaderValue());
            return new ResponseEntity<>(media, headers, HttpStatus.OK);
        } else {
            return new ResponseEntity<>(null, null, HttpStatus.NOT_FOUND);
        }
    }

    @RequestMapping(value = "/getMerchantWebSiteInit")
    public Map<String, Object> getMerchantWebSiteInit() {
        return merchantService.getMerchantWebSiteInit(UserInfoUtils.getMerchantId());
    }

    /**
     * 商户网址是否存在
     *
     * @param siteUrl 商户网址
     * @return true/false
     */
    @RequestMapping(value = "/webSite/isExist")
    @ResponseBody
    public Boolean isSiteUrlExist(@RequestBody String siteUrl) {
        return merchantService.isSiteUrlExist(siteUrl);
    }

    @SystemLogInfo(description = "添加商户网址")
    @RequestMapping(value = "/webSite/add")
    @ResponseBody
    public Boolean addMerchantWebSite(@RequestBody MerchantWebSite merchantWebSite) {
        merchantWebSite.setMerId(UserInfoUtils.getMerchantId());
        return merchantService.addMerchantWebSite(merchantWebSite, UserInfoUtils.getUserName());
    }

    @SystemLogInfo(description = "删除商户网址")
    @RequestMapping(value = "/webSite/delete")
    @ResponseBody
    public List<Integer> deleteMerchantWebSite(@RequestBody List<Integer> idList) {
        return merchantService.deleteMerchantWebSite(idList);
    }

    @SystemLogInfo(description = "修改商户网址")
    @RequestMapping(value = "/webSite/update")
    @ResponseBody
    public Boolean updateMerchantWebSite(@RequestBody MerchantWebSite merchantWebSite) {
        return merchantService.updateMerchantWebSite(merchantWebSite, UserInfoUtils.getUserName());
    }
}